package com.netintech.process.model;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.pagehelper.Page;
import com.netintech.common.utils.file.FileUtils;
import com.netintech.core.aspectj.lang.annotation.Log;
import com.netintech.core.aspectj.lang.enums.BusinessType;
import com.netintech.core.web.controller.BaseController;
import com.netintech.core.web.domain.RequestResult;
import com.netintech.core.web.page.TableDataInfo;
import com.netintech.process.dto.ModelDto;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

import static com.netintech.core.web.domain.RequestResult.error;
import static com.netintech.core.web.domain.RequestResult.success;

/**
 * 流程模型控制器类
 * @author admin
 */
@Controller
public class ProcessModelController extends BaseController implements ModelDataJsonConstants {

    protected static final Logger LOGGER = LoggerFactory.getLogger(ProcessModelController.class);

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ObjectMapper objectMapper;

    private final static String ACTIVITI_CHARSET_NAME = "UTF-8";//工作流字符集名称

    @PostMapping("/process/modeler/list")
    @ResponseBody
    public TableDataInfo list(@RequestBody ModelDto modelEntity) {
        ModelQuery modelQuery = repositoryService.createModelQuery();
        modelQuery.orderByLastUpdateTime().desc();
        // 条件过滤
        if (StringUtils.isNotBlank(modelEntity.getKey())) {
            modelQuery.modelKey(modelEntity.getKey());
        }
        if (StringUtils.isNotBlank(modelEntity.getName())) {
            modelQuery.modelNameLike("%" + modelEntity.getName() + "%");
        }
        Integer pageNum = modelEntity.getPageNum();
        Integer pageSize = modelEntity.getPageSize();
        List<Model> resultList = modelQuery.listPage((pageNum - 1) * pageSize, pageSize);
        Page<Model> list = new Page<>();
        list.addAll(resultList);
        list.setTotal(modelQuery.count());
        list.setPageNum(pageNum);
        list.setPageSize(pageSize);
        return getDataTable(list);
    }

    @GetMapping(value = "/process/modeler/show/{id}")
    public String deploy(ModelMap modelMap, @PathVariable("id") Integer id) {
        modelMap.put("modelId", id);
        return "modeler";

    }


    /**
     * 根据Model部署流程
     */
    @PostMapping(value = "/process/modeler/deploy/{modelId}")
    @ResponseBody
    public RequestResult deploy(@PathVariable("modelId") String modelId) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;

            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);

            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes, ACTIVITI_CHARSET_NAME)).deploy();
            LOGGER.info("部署成功，部署ID=" + deployment.getId());
            return success("部署成功");
        } catch (Exception e) {
            LOGGER.error("根据模型部署流程失败：modelId={}", modelId, e);
            throw new ActivitiException(e.getMessage());
        }
    }

    /**
     * 导出model的xml文件
     */
    @GetMapping(value = "/process/modeler/export/{modelId}")
    @ResponseBody
    public void export(@PathVariable("modelId") String modelId, HttpServletResponse response) {
        OutputStream out;
        try {
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            JsonNode editorNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);

            // 流程非空判断
            if (!CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
                BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
                byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);
                String filename = bpmnModel.getMainProcess().getId() + ".bpmn";
                response.reset();
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);
                response.addHeader("Content-Length", "" + bpmnBytes.length);
                response.setContentType("application/octet-stream; charset=UTF-8");
                IOUtils.write(bpmnBytes, response.getOutputStream());
            }

        } catch (Exception e) {
            LOGGER.error("导出model的xml文件失败：modelId={}", modelId, e);
            try {
                response.sendRedirect("/process/modeler/modelList");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 删除流程模型
     * @param id
     * @return
     */
    @Log(title = "流程模型", businessType = BusinessType.DELETE)
    @DeleteMapping("/process/modeler/remove/{id}")
    @ResponseBody
    public RequestResult remove(@PathVariable("id") String id) {
        try {
            repositoryService.deleteModel(id);
            return returnResult(true);
        }
        catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 流程模型修改
     * @param modelId
     * @param values
     */
    @Log(title = "流程模型", businessType = BusinessType.UPDATE)
    @PostMapping(value="/process/modeler/{modelId}/save")
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public RequestResult saveModel(@PathVariable String modelId, @RequestBody MultiValueMap<String, String> values) {
        try {
            Model model = repositoryService.getModel(modelId);
            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            modelJson.put(MODEL_NAME, values.getFirst("name"));
            modelJson.put(MODEL_DESCRIPTION, values.getFirst("description"));
            model.setMetaInfo(modelJson.toString());
            model.setName(values.getFirst("name"));
            repositoryService.saveModel(model);
            repositoryService.addModelEditorSource(model.getId(), values.getFirst("json_xml").getBytes(ACTIVITI_CHARSET_NAME));
            InputStream svgStream = new ByteArrayInputStream(values.getFirst("svg_xml").getBytes(ACTIVITI_CHARSET_NAME));
            TranscoderInput input = new TranscoderInput(svgStream);
            PNGTranscoder transcoder = new PNGTranscoder();
            // Setup output
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outStream);
            // Do the transformation
            transcoder.transcode(input, output);
            final byte[] result = outStream.toByteArray();
            repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();
            return RequestResult.success();
        } catch (Exception e) {
            LOGGER.error("Error saving model", e);
            throw new ActivitiException("Error saving model", e);
        }
    }

    /**
     * 创建模型
     */
    @PostMapping(value = "/process/modeler/create")
    @ResponseBody
    public RequestResult create(@RequestBody ModelDto model) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, model.getName());
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            //description = StringUtils.defaultString(description);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, model.getDescription());

            Model newModel = repositoryService.newModel();
            newModel.setMetaInfo(modelObjectNode.toString());
            newModel.setName(model.getName());
            newModel.setKey(StringUtils.defaultString(model.getKey()));

            repositoryService.saveModel(newModel);
            repositoryService.addModelEditorSource(newModel.getId(), editorNode.toString().getBytes(ACTIVITI_CHARSET_NAME));

            return new RequestResult(RequestResult.Type.SUCCESS, "创建模型成功", newModel.getId());
        } catch (Exception e) {
            logger.error("创建模型失败：", e);
        }
        return error();
    }
}
